package com.wf.atm.utils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author mpk
 * @since 2024-6-6 14:10:08
 */
public class IOUtils {

    private static File file = new File("src/com/wf/atm/account");
    /**
     * 从指定的文件中读取数据，即反序列化
     *
     * @param fileName the name of the file
     * @return List<Account>
     */
    public static Object readFile(String fileName)  {
        File f = new File( fileName);
        //  找到对应 fileName 文件， 通过字节流拿到 ObjectInputStream.readObject(); 数据
        try (FileInputStream fileInputStream = new FileInputStream(f);
                 ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)) {
            return objectInputStream.readObject();
        } catch (ClassNotFoundException | IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 写入数据到指定文件中
     *
     * @param obj      类型
     * @param fileName 文件名
     */
    public static void writeFile(Object obj, String fileName)   {


        if(!file.exists()){
            file.mkdirs();//创建多层级目录
        }

        // 根据  把数据 写入 fileName 文件中
        try (FileOutputStream fileOutputStream = new FileOutputStream(new File(file, fileName));
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);) {

            objectOutputStream.writeObject(obj);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // obj 数据

    }

    /**
     * @param id       用户账号
     * @param fileName 文件名
     * @throws IOException
     */
    public static void writeId(String id, String fileName)   {



        try (PrintWriter writer = new PrintWriter(fileName)) {

            writer.print(id);

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }


    }

    public static Long readId(String filePath)   {

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(Paths.get(filePath))))) {


            try {
                return Long.parseLong(reader.readLine());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
